
import { reqSaveEvent } from "@/store/actions/apiServices";
import { Toast } from "antd-mobile";
import * as React from "react";
import { useDispatch } from "react-redux";
// Taken from: https://gist.github.com/rikukissa/cb291a4a82caa670d2e0547c520eae53

export function useAddToHomePrompt() {
    // 获取 Redux 分发器
    const dispatch = useDispatch()

    const [prompt, setPrompt] = React.useState(null);


    const onHandleInstallPrompt = () => {
        if (prompt) {
            // return prompt.prompt();
            prompt.prompt()
            prompt.userChoice.then((choiceResult) => {
                console.log(choiceResult)
                if (choiceResult.outcome === 'accepted') {
                    Toast.show('Add success!');
                    //打点
                    reqSaveEvent("ADD_SCREEN_SUCCESS")
                } else {
                    Toast.show('Not agree install short');
                    reqSaveEvent("ADD_SCREEN_NOT_AGREE")
                }
            });
        }
        else {
            Toast.show("beforeinstallprompt not in window!")
            reqSaveEvent("ADD_SCREEN_NOT_SURPORT")
        }
        // return Promise.reject(
        //     new Error(
        //         'Tried installing before browser sent "beforeinstallprompt" event'
        //     )
        // );
    };

    React.useEffect(() => {
        const ready = (e) => {
            e.preventDefault();
            setPrompt(e);
        };
        window.addEventListener("beforeinstallprompt", ready);
        // return () => {
        //     window.removeEventListener("beforeinstallprompt", ready);
        // };
    }, []);

    return [prompt, onHandleInstallPrompt];
}